package com.lx.util.secure.algorithm.summary;


import com.lx.util.secure.algorithm.SummaryAlgorithm;
import com.lx.util.secure.algorithm.coder.CoderType;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class Md5 extends SummaryAlgorithm {


    private static final Md5 MD5 = new Md5();

    public static Md5 getInstance() {
        return MD5;
    }

    @Override
    public String encryptToString(String data){
        return md5(data);
    }

    public static String md5(String data){
        return md5(data.getBytes(StandardCharsets.UTF_8));
    }
    public static String md5(byte[] data){
        try {
            byte[] hash = MessageDigest.getInstance("MD5").digest(data);
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10){
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }


    @Override
    protected CoderType defaultKeyCoderType() {
        return null;
    }

    @Override
    protected CoderType defaultCoderType() {
        return null;
    }

    @Override
    protected String defaultEncryptAlgorithm() {
        return null;
    }

    @Override
    public byte[] encrypt(byte[] bytes) {
        return md5(bytes).getBytes(StandardCharsets.UTF_8);
    }

}
